//
//  CGPersonInfoViewController.m
//  SchoolClient
//
//  Created by mac on 15/10/28.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "CGPersonInfoViewController.h"

@interface CGPersonInfoViewController ()

@property(nonatomic,strong)NSArray *titles;
//@property(nonatomic,strong)NSArray *placeholders;
@property(nonatomic,strong)NSMutableArray *textFields;
@property(nonatomic,strong)UIButton *saveButton;

@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UITextField *nameText;
@property(nonatomic,strong)UITextField *schoolNameText;
@property(nonatomic,strong)UITextField *studentIdText;
@property(nonatomic,strong)UITextField *qqText;
@property(nonatomic,strong)UITextField *idCardText;

@property(nonatomic,strong)UIWindow *coverWindow;
@property(nonatomic,strong)UIView *shadeView;
@property(nonatomic,strong)UIActivityIndicatorView *activity;
@property(nonatomic,strong)UILabel *indicateLabel;

@end

@implementation CGPersonInfoViewController

-(NSArray *)titles{
    if (!_titles) {
        _titles = @[@"姓名",@"大学",@"学号",@"QQ",@"身份证"];
    }
    return _titles;
}

/*
-(NSArray *)placeholders{
    if (!_placeholders) {
        _placeholders = @[@"请输入名字",@"请输入大学",@"请输入学号",@"请输入QQ号",@"请输入身份证号"];
    }
    return _placeholders;
}
*/


-(NSMutableArray *)textFields{
    if (!_textFields) {
        _textFields = [NSMutableArray array];
    }
    return _textFields;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    //添加右导航按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editUserInfo:)];
    
    [self layoutUI];

    
}


-(void)layoutUI{
    
    //底部添加一个scrollowView {{0, 0}, {320, 480}}
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 480-64-100)];
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 316);
    //self.scrollView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.scrollView];
    
    //5个复合文本框
    for (int i = 0 ; i < self.titles.count; i ++) {
        CGRect aFrame = CGRectMake(0, 45*i + 20, SCREEN_WIDTH, 44);
        UIView *containView = [[UIView alloc]initWithFrame:aFrame];
        containView.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:containView];
        
        //标题Lable
        CGRect bFrame = CGRectMake(10, 0, 60, 44);
        UILabel *label = [[UILabel alloc]initWithFrame:bFrame];
        //label.backgroundColor = [UIColor yellowColor];
        label.text = self.titles[i];
        label.font = [UIFont systemFontOfSize:16];
        [containView addSubview:label];
        //输入文本框
        bFrame.origin.x += 60;
        bFrame.size.width = SCREEN_WIDTH - 10 - 60 - 10;
        UITextField *textField = [[UITextField alloc]initWithFrame:bFrame];
        textField.tag = i;
        textField.font = [UIFont systemFontOfSize:16];
        textField.textColor = [UIColor darkGrayColor];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        //textField.placeholder = self.placeholders[i];
        [containView addSubview:textField];
        [textField addTarget:self action:@selector(quitEdit) forControlEvents:UIControlEventEditingDidEndOnExit];
        textField.enabled = NO;
        [self.textFields addObject:textField];
        CGAccountDefault *user = [CGAccountDefault shareAccount];
        switch (i) {
            case 0:
                textField.text = user.name;
                self.nameText = textField;
                break;
            case 1:
                textField.text = user.schoolName;
                self.schoolNameText = textField;
                break;
            case 2:
                textField.text = user.studentId;
                self.studentIdText = textField;
                break;
            case 3:
                textField.text = user.qq;
                self.qqText = textField;
                break;
            default:
                textField.text = user.idCard;
                self.idCardText = textField;
                break;
        }
        
        //NSLog(@"text:%@",textField.text);
    }
    
    
    //保存Button
    CGRect cFrame = CGRectMake(20, 270, SCREEN_WIDTH - 40, 44);
    self.saveButton = [[UIButton alloc]initWithFrame:cFrame];
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.saveButton setBackgroundImage:[UIImage imageNamed:@"login_btn_bg"] forState:UIControlStateNormal];
    self.saveButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.scrollView addSubview:self.saveButton];
    //添加点击事件
    [self.saveButton addTarget:self action:@selector(tapSaveButton) forControlEvents:UIControlEventTouchUpInside];
    self.saveButton.hidden = YES;
}


-(void)editUserInfo:(UIBarButtonItem *)sender{
    
    if ([sender.title isEqualToString:@"编辑"]) {
        sender.title = @"取消";
        self.saveButton.hidden = NO;
        for (UITextField *textField in self.textFields) {
            textField.enabled = YES;
        }
        
    }else{
        sender.title = @"编辑";
        self.saveButton.hidden = YES;
        for (UITextField *textField in self.textFields) {
            textField.enabled = NO;
            
            CGAccountDefault *user = [CGAccountDefault shareAccount];
            switch (textField.tag) {
                case 0:
                    textField.text = user.name;
                    break;
                case 1:
                    textField.text = user.schoolName;
                    break;
                case 2:
                    textField.text = user.studentId;
                    break;
                case 3:
                    textField.text = user.qq;
                    break;
                    
                default:
                    textField.text = user.idCard;
                    break;
            }
            
        }
        
    }
}

-(void)tapSaveButton{
    
    //1.有效性验证,去除字符串两端的空格
    NSString *name = [self.nameText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *schoolName = [self.schoolNameText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *studentId = [self.studentIdText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *qq = [self.qqText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *idCard = [self.idCardText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    [self popShadeView];   //开始转圈
    
    //2.发送注册请求
    CGAccountDefault *user = [CGAccountDefault shareAccount];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"account"] = user.account;
    parameters[@"password"] = user.password;
    parameters[@"tphone"] = user.tphone;
    parameters[@"name"] = name;
    parameters[@"schoolName"] = schoolName;
    parameters[@"studentId"] = studentId;
    parameters[@"qq"] = qq;
    parameters[@"idCard"] = idCard;
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncEncryptRequest:@"/main/updateUserInfo.app" parameters:parameters success:^(id responseData) {
        
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        //NSLog(@"result:%@",result);
        
        [self hidShadeView];  //停止转圈
        
        if ([result rangeOfString:@"account"].location != NSNotFound) {
            
            //保存数据到沙箱
            CGAccount *user = [CGAccount objectWithJSONData:responseData];
            CGAccountDefault *accountDefault = [CGAccountDefault shareAccount];
            
            //姓名
            if ([result rangeOfString:@"name"].location != NSNotFound) {
                accountDefault.name = user.name;
            }else{
                accountDefault.name = nil;
            }
            
            //学校
            if ([result rangeOfString:@"schoolName"].location != NSNotFound) {
                accountDefault.schoolName = user.schoolName;
            }else{
                accountDefault.schoolName = nil;
            }
            
            //学号
            if ([result rangeOfString:@"studentId"].location != NSNotFound) {
                accountDefault.studentId = user.studentId;
            }else{
                accountDefault.studentId = nil;
            }
            
            //QQ号
            if ([result rangeOfString:@"qq"].location != NSNotFound) {
                accountDefault.qq = user.qq;
            }else{
                accountDefault.qq = nil;
            }
            
            //身份证号
            if ([result rangeOfString:@"idCard"].location != NSNotFound) {
                accountDefault.idCard = user.idCard;
            }else{
                accountDefault.idCard = nil;
            }
            
            [accountDefault saveToSandBox];
           
            [Tools alertWithTitle:@"恭喜" andMessage:@"个人信息修改成功!"];
            [self.navigationItem.rightBarButtonItem setTitle:@"编辑"];
            self.saveButton.hidden = YES;
            self.nameText.enabled = NO;
            self.schoolNameText.enabled = NO;
            self.studentIdText.enabled = NO;
            self.qqText.enabled = NO;
            self.idCardText.enabled = NO;
            
        }else{
            
            [Tools alertWithTitle:@"温馨提示" andMessage:@"系统繁忙,请稍后再试"];
        }

    } failure:^(NSError *error) {
        
        [self hidShadeView];  //停止转圈
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试!"];
        return ;
    }];
    
}



#pragma mark 退出键盘
-(void)quitEdit{
    
    [self.view endEditing:YES];
    
}

#pragma mark 弹出网络延时加载框
-(void)popShadeView{
    
    self.shadeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.shadeView.backgroundColor = [UIColor blackColor];
    self.shadeView.alpha = 0.3;
    self.coverWindow = [UIApplication sharedApplication].keyWindow;
    [self.coverWindow addSubview:self.shadeView];
    
    //添加一个等待进度轮
    self.activity = [[UIActivityIndicatorView alloc]init];
    self.activity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    self.activity.color = [UIColor blueColor];
    CGPoint center = self.shadeView.center;
    center.y -= 50;
    self.activity.center = center;
    [self.activity startAnimating];
    [self.coverWindow addSubview:self.activity];
    
    //添加一个提示Label
    self.indicateLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.activity.frame)+10, SCREEN_WIDTH, 44)];
    self.indicateLabel.textAlignment = NSTextAlignmentCenter;
    self.indicateLabel.font = [UIFont systemFontOfSize:14];
    self.indicateLabel.textColor = [UIColor blueColor];
    self.indicateLabel.text = @"信息保存中...";
    [self.coverWindow addSubview:self.indicateLabel];
    
}

#pragma mark 取消网络延时加载框
-(void)hidShadeView{
    
    self.shadeView.hidden = YES;
    self.indicateLabel.hidden = YES;
    [self.activity stopAnimating];
    
}


#pragma mark 注册键盘通知
-(void)viewWillAppear:(BOOL)animated{
    /*
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
     */
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(openKeyboard:) name:UIKeyboardDidShowNotification object:nil];
    [center addObserver:self selector:@selector(closeKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    
}

//键盘弹起时
-(void)openKeyboard:(NSNotification *)notification{
    
    if (IS_IPHONE4) {
        //self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 529);
        self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 480);
    }else if (IS_IPHONE5) {
        self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 392);
        
    }
    
}

//键盘收起时
-(void)closeKeyboard:(NSNotification*)notification{
    
    self.scrollView.contentSize =  CGSizeMake(SCREEN_WIDTH, 316);
}



@end
